<?php
if (!defined('BASEPATH'))
	exit('No direct script access allowed');

require_once APPPATH . 'third_party/wxpay/WxPay.Api.php';
require_once APPPATH . 'third_party/wxpay/WxPay.Data.php';

class Wxpay {
	private $wxPayApi = NULL;
	
	function __construct() {
		$this->wxPayApi = new WxPayApi();
	}
	
	public function refund($data, $timeOut = 6) {
		$inputObj = new WxPayRefund();
		$inputObj->SetTransaction_id($data['ext_order_num']);
		$inputObj->SetOut_refund_no($data['refund_num']);
		$inputObj->SetTotal_fee($data['netpay'] * 100);
		$inputObj->SetRefund_fee($data['netpay'] * 100);
		$inputObj->SetOp_user_id($data['op_user_id']);
		
		return $this->wxPayApi->refund($inputObj, $timeOut);
	}
	
	public function createApiOrder($data, $timeOut = 6) {
		$inputObj = new WxPayUnifiedOrder();
		$body = "【{$data['details'][0]['name']}】等{$data['request_num']}件商品";
		$details = '';
		foreach ($data['details'] as $v) {
			$details .= "【{$v['name']}】 x{$v['number']}\n";
		}
		$inputObj->SetBody($body);
		$inputObj->SetDetail($details);
		$inputObj->SetOut_trade_no($data['order_num']);
		$inputObj->SetTotal_fee($data['netpay'] * 100);
		$inputObj->SetTrade_type('APP');
		$inputObj->SetAttach($data['id']);
		$inputObj->SetNotify_url(base_url('notify.php'));

		return $this->wxPayApi->unifiedOrder($inputObj, $timeOut);
	}
	
	public function getNonceStr($length = 32) {
		return $this->wxPayApi->getNonceStr($length);
	}
	/**
	 * 格式化参数格式化成url参数
	 */
	public function ToUrlParams()
	{
		$buff = "";
		foreach ($this->values as $k => $v)
		{
			if($k != "sign" && $v != "" && !is_array($v)){
				$buff .= $k . "=" . $v . "&";
			}
		}
		
		$buff = trim($buff, "&");
		return $buff;
	}		
	/**
	 * 生成签名
	 * @return 签名，本函数不覆盖sign成员变量，如要设置签名需要调用SetSign方法赋值
	 */
	public function MakeSign($data)
	{
		//签名步骤一：按字典序排序参数
		ksort($data);
		$string = "";
		foreach ($data as $k => $v)
		{
			if($k != "sign" && $v != "" && !is_array($v)){
				$string .= $k . "=" . $v . "&";
			}
		}
		//签名步骤二：在string后加入KEY
		$string .= "key=".WxPayConfig::KEY;
		//签名步骤三：MD5加密
		$string = md5($string);
		//签名步骤四：所有字符转为大写
		$result = strtoupper($string);
		return $result;
	}
}